/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package moodlerest;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Hashtable;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

/**
 * Class containing the static routines to manipulate the enrolment information within Moodle. Currently there is no method to obtain the contextid of a course through web services to initialise MoodleEnrolUser objects.
 * @see MoodleCourseUser
 * @see MoodleEnrolUser
 * @author bill
 */
public class MoodleRestEnrol {

    private static final int BUFFER_MAX=4000;

    /**
     * Method to get all the enrolled users of a course with the given capability in the selected group who have the required active status.
     * @param courseid long
     * @param withcapability String
     * @param groupid long
     * @param onlyactive boolean
     * @return users MoodleCourseUser[]
     * @throws MoodleRestEnrolException
     * @throws UnsupportedEncodingException
     */
    public static MoodleCourseUser[] getEnrolledUsers(long courseid, String withcapability, long groupid, boolean onlyactive) throws MoodleRestEnrolException , UnsupportedEncodingException {
        StringBuilder data=new StringBuilder();
        Vector v=new Vector();
        if (MoodleRestWebService.getAuth()==null)
            throw new MoodleRestEnrolException();
        else
            data.append(MoodleRestWebService.getAuth());
        data.append("&").append(URLEncoder.encode("wsfunction", "UTF-8")).append("=").append(URLEncoder.encode("moodle_enrol_get_enrolled_users", "UTF-8"));
        if (courseid<0) throw new MoodleRestEnrolException(); else data.append("&").append(URLEncoder.encode("courseid", "UTF-8")).append("=").append(URLEncoder.encode(""+courseid, "UTF-8"));
        if (withcapability==null || withcapability.equals("")) throw new MoodleRestEnrolException(); else data.append("&").append(URLEncoder.encode("withcapability", "UTF-8")).append("=").append(URLEncoder.encode(withcapability, "UTF-8"));
        if (groupid<0) throw new MoodleRestEnrolException(); else data.append("&").append(URLEncoder.encode("groupid", "UTF-8")).append("=").append(URLEncoder.encode(""+groupid, "UTF-8"));
        data.append("&").append(URLEncoder.encode("onlyactive", "UTF-8")).append("=").append(URLEncoder.encode(""+(onlyactive?1:0), "UTF-8"));
        Document document = MoodleRestWebService.call(data.toString());
        NodeList elements = Util.getValueElementsFromXML(document);
        MoodleCourseUser user=null;
        for (int j=0;j<elements.getLength();j+=2) {
            String content1=elements.item(j).getTextContent();
            String content2=elements.item(j+1).getTextContent();
            user=new MoodleCourseUser(Long.parseLong(content1),Long.parseLong(content2));
            v.add(user);
        }
        MoodleCourseUser[] users=new MoodleCourseUser[v.size()];
        for (int i=0;i<v.size();i++) {
            users[i]=(MoodleCourseUser)v.get(i);
        }
        v.removeAllElements();
        return users;
    }

    /**
     * Method to enrol a user in a Moodle course. Needs the contextid and roleid so problem!
     * @param user MoodleEnrolUser
     * @throws UnsupportedEncodingException
     * @throws MoodleRestEnrolException
     */
    public static void enrolUser(MoodleEnrolUser user) throws UnsupportedEncodingException, MoodleRestEnrolException {
        MoodleEnrolUser[] a=new MoodleEnrolUser[1];
        a[0]=user;
        enrolUsers(a);
    }

    /**
     * Method to enrol a number of users on Moodle courses. Needs the contextids and roleids so problem!
     * @param user MoodleEnrolUser[]
     * @throws UnsupportedEncodingException
     * @throws MoodleRestEnrolException
     */
    public static void enrolUsers(MoodleEnrolUser[] user) throws UnsupportedEncodingException, MoodleRestEnrolException {
        Hashtable hash=new Hashtable();
        boolean processed=false;
        try {
            StringBuilder data=new StringBuilder();
            if (MoodleRestWebService.getAuth()==null)
                throw new MoodleRestEnrolException();
            else
                data.append(MoodleRestWebService.getAuth());
            data.append("&").append(URLEncoder.encode("wsfunction", "UTF-8")).append("=").append(URLEncoder.encode("moodle_role_assign", "UTF-8"));
            for (int i=0;i<user.length;i++) {
                if (user[i]==null) throw new MoodleRestEnrolException();
                if (user[i].getRoleId()==-1) throw new MoodleRestEnrolException(); else data.append("&").append(URLEncoder.encode("assignments["+i+"][roleid]", "UTF-8")).append("=").append(URLEncoder.encode(""+user[i].getRoleId(), "UTF-8"));
                if (user[i].getUserId()==-1) throw new MoodleRestEnrolException(); else data.append("&").append(URLEncoder.encode("assignments["+i+"][userid]", "UTF-8")).append("=").append(URLEncoder.encode(""+user[i].getUserId(), "UTF-8"));
                if (user[i].getContextId()==-1) throw new MoodleRestEnrolException(); else data.append("&").append(URLEncoder.encode("assignments["+i+"][contextid]", "UTF-8")).append("=").append(URLEncoder.encode(""+user[i].getContextId(), "UTF-8"));
                if (data.length()>=BUFFER_MAX) {
                    processed=true;
                    data.trimToSize();
                    Document document = MoodleRestWebService.call(data.toString());
                    NodeList elements = Util.getValueElementsFromXML(document);
                    data=new StringBuilder();
                    data.append(MoodleRestWebService.getAuth());
                    data.append("&").append(URLEncoder.encode("wsfunction", "UTF-8")).append("=").append(URLEncoder.encode("moodle_role_assign", "UTF-8"));
                } else
                    processed=false;
            }
            if (!processed) {
                data.trimToSize();
                Document document = MoodleRestWebService.call(data.toString());
                NodeList elements = Util.getValueElementsFromXML(document);
            }
        }  catch (IOException ex) {
            Logger.getLogger(MoodleRestEnrol.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Method to un-enrol a user from a Moodle course.
     * @param user MoodleEnrolUser
     * @throws UnsupportedEncodingException
     * @throws MoodleRestEnrolException
     */
    public static void unenrolUser(MoodleEnrolUser user) throws UnsupportedEncodingException, MoodleRestEnrolException {
        MoodleEnrolUser[] a=new MoodleEnrolUser[1];
        a[0]=user;
        unenrolUsers(a);
    }

    /**
     * Method to un-enrol a number of users from Moodle courses.
     * @param user MoodleEnrolUser[]
     * @throws UnsupportedEncodingException
     * @throws MoodleRestEnrolException
     */
    public static void unenrolUsers(MoodleEnrolUser[] user) throws UnsupportedEncodingException, MoodleRestEnrolException {
        Hashtable hash=new Hashtable();
        boolean processed=false;
        try {
            StringBuilder data=new StringBuilder();
            if (MoodleRestWebService.getAuth()==null)
                throw new MoodleRestEnrolException();
            else
                data.append(MoodleRestWebService.getAuth());
            data.append("&").append(URLEncoder.encode("wsfunction", "UTF-8")).append("=").append(URLEncoder.encode("moodle_role_unassign", "UTF-8"));
            for (int i=0;i<user.length;i++) {
                if (user[i]==null) throw new MoodleRestEnrolException();
                if (user[i].getRoleId()==-1) throw new MoodleRestEnrolException(); else data.append("&").append(URLEncoder.encode("unassignments["+i+"][roleid]", "UTF-8")).append("=").append(URLEncoder.encode(""+user[i].getRoleId(), "UTF-8"));
                if (user[i].getUserId()==-1) throw new MoodleRestEnrolException(); else data.append("&").append(URLEncoder.encode("unassignments["+i+"][userid]", "UTF-8")).append("=").append(URLEncoder.encode(""+user[i].getUserId(), "UTF-8"));
                if (user[i].getContextId()==-1) throw new MoodleRestEnrolException(); else data.append("&").append(URLEncoder.encode("unassignments["+i+"][contextid]", "UTF-8")).append("=").append(URLEncoder.encode(""+user[i].getContextId(), "UTF-8"));
                if (data.length()>=BUFFER_MAX) {
                    processed=true;
                    data.trimToSize();
                    Document document = MoodleRestWebService.call(data.toString());
                    NodeList elements = Util.getValueElementsFromXML(document);
                    data=new StringBuilder();
                    data.append(MoodleRestWebService.getAuth());
                    data.append("&").append(URLEncoder.encode("wsfunction", "UTF-8")).append("=").append(URLEncoder.encode("moodle_role_unassign", "UTF-8"));
                } else
                    processed=false;
            }
            if (!processed) {
                data.trimToSize();
                Document document = MoodleRestWebService.call(data.toString());
                NodeList elements = Util.getValueElementsFromXML(document);
            }
        }  catch (IOException ex) {
            Logger.getLogger(MoodleRestEnrol.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
